<script lang="ts">
  import { user$ } from "@store/entity/User";
  import { currentDataset$ } from "@store/entity/dataset";
  import { renameCurrentDataset, updateCurrentDatasetDesc } from "@service/dataset"
  import { Icon } from "@component/icons";

  $: isOwner = $user$.id === $currentDataset$.user_id
  $: datasetName = $currentDataset$?.name || ""
  $: datasetDesc = $currentDataset$?.desc || ""

  let isEditingName: boolean
  let isEditingDesc: boolean

  let editingName: string
  let editingDesc: string

  function enterEditingName (el: HTMLElement) {
    editingName = datasetName
    el.focus();
  }
  async function exitEditingName () {
    isEditingName = false
    let isDiff = editingName !== datasetName
    if (!isDiff) {
      return
    }
    await renameCurrentDataset(editingName)
  }
  function enterEditingDesc (el: HTMLElement) {
    editingDesc = datasetDesc
    el.focus();
  }
  async function exitEditingDesc () {
    isEditingDesc = false
    let isDiff = editingDesc !== datasetDesc
    if (!isDiff) {
      return
    }
    await updateCurrentDatasetDesc(editingDesc)
  }
</script>
<div class="flex-container justify-start flex-row w-full h-full space-x-2 pl-4">
  <div class="flex-center-box w-20 h-20 text-4xl shadow-xl text-center rounded-full bg-green-800 text-gray-200">
    {datasetName.substring(0, 1)}
  </div>
  <div class="flex-container items-start w-96 flex-col h-full">
    {#if (isEditingName)}
      <input type="text" class="input py-1 mt-1" bind:value={editingName} on:keypress={(e)=>{ e.key === 'Enter' && exitEditingName()}} on:blur={exitEditingName} use:enterEditingName>
    {:else}
      <div class="flex-container justify-start flex-row text-2xl grow" >
        {datasetName}
        {#if isOwner}
          <!-- svelte-ignore a11y-missing-attribute -->
          <!-- svelte-ignore a11y-click-events-have-key-events -->
          <a class="cursor-pointer" on:click={() => isEditingName = true}><Icon name="pencil-alt" size="sm+" className="ml-2"  /></a>
        {/if}
      </div>
    {/if}
    <div class="flex-center-box justify-start italic w-full indent-4 h-12 flex-none text-sm">
    {#if (isEditingDesc)}
      <input type="text" class="input py-1 mt-1" bind:value={editingDesc} on:keypress={(e)=>{ e.key === 'Enter' && exitEditingDesc()}} on:blur={exitEditingDesc} use:enterEditingDesc>
    {:else}
      <!-- svelte-ignore a11y-missing-attribute -->
      <!-- svelte-ignore a11y-click-events-have-key-events -->
      {#if isOwner}
        <a class="cursor-pointer w-full block" on:click={() => isEditingDesc = true}>{datasetDesc || "<补充描述>"}</a>
      {/if}
    {/if}
  </div>
  </div>
</div>